package com.right.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.Tools.PageData;
import com.commons.AjaxResponse;
import com.google.gson.Gson;
import com.right.dao.FoodsDao;
import com.right.dao.OrdersDao;
import com.right.dao.impl.FoodsDaoImpl;
import com.right.dao.impl.OrdersDaoImpl;
import com.right.entity.Cart;
import com.right.entity.Foods;
import com.right.entity.Orderdetail;
import com.right.entity.Orders;
import com.right.entity.Store;
import com.right.entity.Users;
import com.right.service.OrderdetailService;
import com.right.service.OrdersService;
import com.right.service.UserService;
import com.right.service.impl.OrderdetailServiceImpl;
import com.right.service.impl.OrdersServiceImpl;
import com.right.service.impl.UserServiceImpl;

/**
 * Servlet implementation class OrderServlet
 */
@WebServlet("/OrdersServlet")
public class OrdersServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	// 接口引用 指向 实现类对象
	OrdersDao ordersDao = new OrdersDaoImpl();
	UserService userService = new UserServiceImpl();
	OrdersService orderServlet = new OrdersServiceImpl();
	FoodsDao foodsDao = new FoodsDaoImpl();
	OrderdetailService os = new OrderdetailServiceImpl();

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String op = "";
		if (request.getParameter("op") != null) {
			op = request.getParameter("op");
		}
		System.out.println(op);
		if ("add".equals(op)) {
			doAdd(request, response);
		}  else if ("cart".equals(op)) {
			//购物车提交到订单页
			doCart(request, response);
		} else if ("queryByUsers".equals(op)) {
			HttpSession session = request.getSession();
			Users users = (Users) session.getAttribute("users");
			// 读取用户的id
			int userid = users.getUserid();
			// 查询订单信息(用户)
			doQueryOrdersByUseridPage(request, response, userid);
		} else if ("queryByStore".equals(op)) {
			// 读取商家的店名
			String store = request.getParameter("store");
			// 查询订单信息(商家)
			doQueryOrdersByStorePage(request, response, store);
		} else if ("selectByPage".equals(op)) {
			doSelectByPage(request, response);
		} else if ("".equals(op)) {
			response.sendRedirect("main.jsp");
		} else if ("del".equals(op)) {
			doAjaxDel(request, response);
		} else if ("update".equals(op)) {
			// 修改菜品
			doUpdateFoods(request, response);
		}
	}
	
	private void doUpdateFoods(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 获取请求的参数
		String orderid = request.getParameter("orderid");
		String store = request.getParameter("store");
		double total = Double.parseDouble(request.getParameter("total"));
		String address = request.getParameter("address");
		int orderstatus = Integer.parseInt(request.getParameter("orderstatus"));
		String starttime = request.getParameter("starttime");
		int userid = Integer.parseInt(request.getParameter("userid"));
		String usercall = request.getParameter("usercall");
		String storecall = request.getParameter("storecall");
		String orderinfo = request.getParameter("orderinfo");
		
		// 构造一个foods对象
		Orders orders = new Orders(orderid, store, total, address, orderstatus, starttime, userid, usercall, storecall, orderinfo);
		System.out.println(orders);
		boolean flag = orderServlet.updateOrdersByEndtime(orders);
		System.out.println(flag);
		// 根据flag的结果进行转发或者提示
		if (flag) {
			// 转发到查询菜品的界面
			request.setAttribute("msg", "修改成功！");
			request.getRequestDispatcher("s-orders.jsp").forward(request, response);
//				doSelectByPage(request, response);
		} else {
			// 修改失败给提示转发回到修改的页面
			request.setAttribute("msg", "修改失败！");
			request.getRequestDispatcher("s-orders.jsp").forward(request, response);
		}

	}
	
	private void doAjaxDel(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1.设置响应头的contentType
		response.setContentType("application/json;charset=utf-8");

		// 先获取请求参数的值
		String orderid = null;

		if (request.getParameter("orderid") != null) {
			orderid = request.getParameter("orderid");
		}
		System.out.println(orderid);
		// 2 调用 service的方法
		boolean flag = orderServlet.delOrdersById(orderid);
		System.out.println(flag);
		AjaxResponse res = new AjaxResponse(flag + "", 200);
		// 3将list转换为json格式的字符串
		Gson gson = new Gson();
		String jsonString = gson.toJson(res);

		// 4 响应
		PrintWriter outPrintWriter = response.getWriter();
		outPrintWriter.print(jsonString);

		// 5.关闭
		outPrintWriter.close();
	}

	/**
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void doCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//购物车提交到订单页
		HttpSession session = request.getSession();
		Users users = (Users) session.getAttribute("users");
		if (users == null) {
			request.setAttribute("msg", "用户未登录");
			request.getRequestDispatcher("userlogin.jsp").forward(request, response);
		} else {
			Cart cart = (Cart) session.getAttribute("cart");
			int t1 = 3;
			HashMap<Integer, Orderdetail> map = cart.getCartItems();
			Set<Integer> i=map.keySet();
			for (Integer t : i) {
				t1=t;
				break;
			}
			System.out.println(t1);
			String foodsname = cart.getCartItems().get(t1).getFoods().getFoodsname();
			Store store = foodsDao.getStoreByFoods(foodsname);
			// System.out.println("store"+store);
			request.setAttribute("users", users);
			request.setAttribute("cart", cart);
			request.setAttribute("store", store);
			request.getRequestDispatcher("ordersubmit.jsp").forward(request, response);
		}
	}

	private void doSelectByPage(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String keywords = "";
		// 获取请求参数
		if (request.getParameter("keywords") != null) {
			keywords = request.getParameter("keywords");
		}
		// 页码默认值在第一页
		int page = 1;
		// 每页默认10条记录
		int pageSize = 10;
		if (request.getParameter("page") != null) {
			page = Integer.parseInt(request.getParameter("page"));
		}

		if (request.getParameter("pageSize") != null) {
			pageSize = Integer.parseInt(request.getParameter("pageSize"));
		}
		// 调用查询菜品的Service方法
		PageData<Orders> pData = orderServlet.getOrdersByStoreByPage(page, pageSize, keywords);

		// 传递PageData对象给jsp
		request.setAttribute("pData", pData);
		// 转发回来的时候，将查询关键字也存储在request范围内
		request.setAttribute("keywords", keywords);
		// 转发到评论列表
		request.getRequestDispatcher("s-orders.jsp").forward(request, response);

	}

	private void doAdd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 1获取请求的参数,要先判断是否为空[需要有服务器端验证]
		// 获取用户，购物车和商家对象
		HttpSession session = request.getSession();
		Cart cart = (Cart) session.getAttribute("cart");
		System.out.println("********");
		String orderid = request.getParameter("orderid");
		String store = request.getParameter("store");// 店名
		double total = Double.parseDouble(request.getParameter("total"));
		String address = request.getParameter("address");
		int orderstatus = Integer.parseInt(request.getParameter("orderstatus"));
		Users users = (Users) session.getAttribute("users");
		int userid = users.getUserid();
		String usercall = request.getParameter("usercall");
		String storecall = request.getParameter("storecall");// 商家联系方式
		String orderinfo = request.getParameter("orderinfo");// 订单备注

		// 重复提交 -III 增加了一个判断是否为重复提交的操作
		String tokenSession = (String) request.getSession().getAttribute("token");
		String tokenRequest = request.getParameter("token");

		// 重复提交的判断
		if (tokenSession == null || tokenRequest == null || !tokenSession.equals(tokenRequest)) {
			// 重复提交了
			request.setAttribute("msg", "重复提交了!请勿刷新!");
			request.getRequestDispatcher("ordersubmit.jsp").forward(request, response);
		} else {

			// 2构造一个orders对象
			Orders orders = new Orders(orderid, store, total, address, orderstatus, userid, usercall, storecall,
					orderinfo);
			boolean flag = orderServlet.addOrdersAndOrderdetail(orders, cart);

			System.out.println(flag);
			// 4根据返回结果进行转发或者提示等
			if (flag) {

				request.getRequestDispatcher("OrdersServlet?op=queryByUsers").forward(request, response);

			} else {
				// 转发到回到orders增加的页面
				// 失败分两种情况，一种是如果名字重复；另外可能发生异常
				request.setAttribute("msg", "下单失败！请重新添加。");
				request.getRequestDispatcher("ordersubmit.jsp").forward(request, response);

			}
		}
	}

	private void doQueryOrdersByUseridPage(HttpServletRequest request, HttpServletResponse response, int userid)
			throws ServletException, IOException {
		//根据当前登录的用户获取订单集合
		List<Orders> orders = ordersDao.getOrdersByUserid(userid);
		//System.out.println("userid"+userid);
//		String orderid = orders.get(0).getOrderid();
//		List<Orderdetail> detail = os.getOrderdetails(orderid);
		// 传递订单orders给jsp
		request.setAttribute("orders", orders);
//		request.setAttribute("orderdetail", detail);
		// 转发
		request.getRequestDispatcher("personinfo.jsp").forward(request, response);
	}

	private void doQueryOrdersByStorePage(HttpServletRequest request, HttpServletResponse response, String store)
			throws ServletException, IOException {
		// 转发到显示servelt上进行查询，直接调用doGetOrdersByUseridPage的方法即可。
		String keywords = "";
		// 2获取请求参数
		if (request.getParameter("keywords") != null) {
			keywords = request.getParameter("keywords");
		}
		// 页码默认为1
		int page = 1;
		// 每页记录数默认为10
		int pageSize = 10;
		if (request.getParameter("page") != null) {
			page = Integer.parseInt(request.getParameter("page"));
		}
		if (request.getParameter("pageSize") != null) {
			pageSize = Integer.parseInt(request.getParameter("pageSize"));
		}

		// 3 调用 dao的方法
		PageData<Orders> pd = orderServlet.getOrdersByStorePage(page, pageSize, store);
		// 4传递list给jsp
		request.setAttribute("pd", pd);
		// 传递keyword给jsp
		request.setAttribute("keywords", keywords);
		// 5 转发
		request.getRequestDispatcher("s-orders.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
